#include "TcpServer.hpp"
#include <memory>
#include "Comm.hpp"
#include"Translate.hpp"
#include<cctype>
#include<algorithm>
#include"Daemon.hpp"
using namespace std;

void Interact(int sockfd, string& out,string in)
{
    char buffer[1024];
    size_t n = read(sockfd, buffer, sizeof(buffer) - 1);
    if (n > 0)
    {
        buffer[n] = 0;
        // cout << "client say#  " << buffer << endl;
        //cout << addr.PrintDebug() << "$" << buffer << endl;

        //string echo_string="pong";
        // string echo_string = "server say#";
        // echo_string += buffer;
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0) // read如果返回值是0，表示读到了文件的结尾（对端关闭了）
    {
        lg.LogMessage(Info, "client close the connection\n");
    }
    else
    {
        lg.LogMessage(Error, "read socket error,errno code:%d,error string:%s\n", errno, strerror(errno));
    }
}


//未来的服务器是部署在你的云服务器上的，你是怎么知道你的服务在未来任何一个时刻，都是正常的呢？
//我们可以定期30s向我们的服务器发送一个请求，如果得到了回复，说明我们的服务是正常的。
//这种机制，我们称之为心跳机制，我们可以问client->服务器，反向的server->client，问问对方是否还在线。
void Ping(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd:%d\n", addr.PrintDebug().c_str(), "ping", sockfd);
    
    //
    string message;
    Interact(sockfd, message,"pong");
    
}

Translate translate;

void Translate(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd:%d\n", addr.PrintDebug().c_str(), "translate", sockfd);
    //string word;
    char wordbuf[128];
    int n=read(sockfd, wordbuf, sizeof(wordbuf) - 1);
    if(n>0)
        wordbuf[n] = 0;
    string chinese=translate.Excute(wordbuf);
    write(sockfd, chinese.c_str(), chinese.size());

    lg.LogMessage(Debug, "%s translate servervice %s to %s\n", addr.PrintDebug().c_str(),wordbuf, chinese.c_str());
}

void Transform(int sockfd, InetAddr addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd:%d\n", addr.PrintDebug().c_str(), "transform", sockfd);
    char message[108];
    int n=read(sockfd, message, sizeof(message) - 1);
    if(n>0)
        message[n] = 0;
    
    string messagebuf=message;
    transform(messagebuf.begin(), messagebuf.end(),messagebuf.begin(),[](unsigned char c){return toupper(c);});
    write(sockfd, messagebuf.c_str(), messagebuf.size());
}

// void Default(int sockfd, InetAddr addr)
// {
//     lg.LogMessage(Debug, "%s select %s success, fd:%d\n", addr.PrintDebug().c_str(), "default", sockfd);
    
// }

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        cout << "Usage:\n     ./udp_echo_server <port>" << endl;
        return Usage_Err;
    }

    uint16_t port = stoi(argv[1]);

    Daemon(false,false);//开启守护进程

    TcpServer *tsvr = new TcpServer(port);

    tsvr->RegisterFunc("ping", Ping);
    tsvr->RegisterFunc("translate", Translate);
    tsvr->RegisterFunc("transform", Transform);
   // tsvr->RegisterFunc("default", Default);//?

    tsvr->Init();


    tsvr->Start();
    return 0;
}